package demo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author ：黄淼淳
 * @date ：2021/12/18 23:31
 * @description：读写锁测试
 */
public class ReadWriteLockDemo {
    Map<String,String> map = new HashMap<>();
    ReadWriteLock lock = new ReentrantReadWriteLock();

    String read(String key){
        lock.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t 读数据");
            try{TimeUnit.SECONDS.sleep(3);} catch( InterruptedException e){e.printStackTrace();}
            String result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t 读取完成");
            return result;
        } finally {
            lock.readLock().unlock();
        }
    }

    void write(String key,String value){
        lock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t 写数据");
            try{TimeUnit.SECONDS.sleep(3);} catch( InterruptedException e){e.printStackTrace();}
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t 写完成");
        } finally {
            lock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {
        ReadWriteLockDemo demo = new ReadWriteLockDemo();
        for (int i = 0; i < 10; i++) {
            final String x = i+"";
            new Thread(()->{
                demo.read(x);
                demo.write(x,x);
            },String.valueOf(i+1)).start();
        }
    }
}
